(function ($){
    $.fn.calendar = function (options){            
    
        var defaults = {
            year: '.year',                  //年份选择器
            month: '.month',                //月份选择器
            prevMonth: '#J_prev-btn',       //切换上个月
            nextMonth: '#J_next-btn',       //切换下个月
            calendarArea: '#dayWrap ul',    //日历生成区域
            nowDate: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate(),   //今天的日期
            todayClass: 'cur-date',         //今天的class名
            highColor: 'active',            //高亮的class名
            y: new Date().getFullYear(),     //初始化的年
            m: new Date().getMonth() + 1,    //初始化的月
            d: new Date().getDate(),          //初始化的日
            countDay: 42,                      //日历最多显示多少格（最多6行，一行7格，6 x 7 = 42）
            nextMonthSelect: true,          //大于本月的不能切换到下个月，默认 true 表示不能切换
        };
        var opts = $.extend(defaults, options);


        // 获取当前年月日
        var nowDate = opts.nowDate.split('-'),
            nowYear = nowDate[0],
            nowMonth = nowDate[1],
            nowDate = nowDate[2];


        var cale = {
            //初始化年月日
            y: 2017,
            m: 6,
            d: 1,
            countDay: 42, //日历最多显示多少格（最多6行，一行7格，6 x 7 = 42）
            init: function (){

                document.querySelector('.year-title').innerText = opts.y;
                document.querySelector('.month-title').innerText = opts.m;

                var prevDay         = new Date(opts.y,opts.m-1,1).getDay();   //当月的上一月显示几天
                var nowDay          = new Date(opts.y,opts.m,0).getDate();  //当月有多少天
                var prevMonthDay    = new Date(opts.y,opts.m-1,0).getDate();  //上个月有多少天
                var nextDay         = opts.countDay - nowDay - prevDay;  //当月的下一月显示几天

                console.log( prevDay,nowDay,nextDay );

                var oDate = new Date();
                var oYear = oDate.getFullYear(),
                    oMonth = oDate.getMonth(),
                    oDay = oDate.getDate();

                // console.log(oYear, oMonth, oDay);

                oDate.setDate(1);
                var weekday = ['日','一','二','三','四','五','六'];
                var startWeek = weekday[oDate.getDay()];    //1号对应星期几
                // console.log('1号对应星期',startWeek);
                var str = '';

                //遍历当月的上一月剩余天数
                for(var i = (prevDay-1); i >= 0; i--){
                    str += '<li class="pre" data-date="'+opts.y+'-'+cale.toDouble((opts.m-1))+'-'+cale.toDouble((prevMonthDay-i))+'" title="'+opts.y+'-'+cale.toDouble((opts.m-1))+'-'+cale.toDouble((prevMonthDay-i))+'">'+ (prevMonthDay-i) +'</li>';
                }

                //遍历当月日期
                for(var i = 1; i <= nowDay; i++){
                    str += '<li class="date" data-date="'+opts.y+'-'+cale.toDouble(opts.m)+'-'+cale.toDouble(i)+'" title="'+opts.y+'-'+cale.toDouble(opts.m)+'-'+cale.toDouble(i)+'">'+ i +'</li>';
                }

                //遍历当月的下一月剩余天数
                for(var i = 1; i <= nextDay; i++){
                    // console.log(i);
                    str += '<li class="next" data-date="'+opts.y+'-'+cale.toDouble((opts.m+1))+'-'+cale.toDouble(i)+'" title="'+opts.y+'-'+cale.toDouble((opts.m+1))+'-'+cale.toDouble(i)+'">'+ i +'</li>';
                }


                var caleWrap = document.querySelector('.cale-day');
                var caleBox = caleWrap.querySelector('ul');
                caleBox.innerHTML = str;

                //今天
                $('.cale-day li[data-date='+ oYear + '-' + cale.toDouble(oMonth+1) + '-' + cale.toDouble(oDay) + ']').addClass('cur-date active');

                //大于今天的日期不能选择
                $('.cale-day').find('.cur-date').nextAll().addClass('disabled');
            },
            //切换上一个月，下一个月
            onChange: function (){

                var prevBtn = document.querySelector('#J_prev-btn'),
                    nextBtn = document.querySelector('#J_next-btn');

                //上个月
                prevBtn.onclick = function (){
                    // console.log(cale.m);
                    if(opts.m == 1){
                        opts.m = 13;
                        opts.y = +opts.y - 1;
                    }
                    // console.log(opts.m, opts.y);
                    opts.m = +opts.m - 1;
                    document.querySelector('.year-title').innerText = opts.y;
                    document.querySelector('.month-title').innerText = opts.m;
                    cale.init();
                }

                //下个月
                nextBtn.onclick = function (){
                    if( opts.nextMonthSelect ){
                        //超过本月的不能切换到下个月
                        if( $('.cale-day li').hasClass('disabled') ){
                            return;
                        }
                    }

                    console.log( opts.m );

                    if( opts.m >= 12 ){
                        opts.m = 0;
                        opts.y = +opts.y + 1;
                    }
                    opts.m = +opts.m + 1;   // + 字符串转数字
                    document.querySelector('.year-title').innerText = opts.y;
                    document.querySelector('.month-title').innerText = opts.m;
                    cale.init();
                }
            },
            //选中日期
            onSelect: function (){

                $('.cale-day').on('click', 'li', function (){
                    if( !$(this).hasClass('disabled') && !$(this).hasClass('pre') && !$(this).hasClass('next') ){
                        $(this).addClass(opts.highColor).siblings().removeClass(opts.highColor);
                        console.log( $(this).data('date') );
                        $('#date').val( $(this).data('date') );
                    }else if( $(this).hasClass('pre') ){

                        if(opts.m == 1){
                            opts.m = 13;
                            opts.y -= 1;
                        }
                        console.log(opts.m, opts.y);
                        opts.m = opts.m - 1;
                        document.querySelector('.year-title').innerText = opts.y;
                        document.querySelector('.month-title').innerText = opts.m;
                        cale.init();

                        //选择日期高亮
                        var selectDate  = $(this).data('date'),
                            $li         = $('.cale-day li');

                        for(var i = 0; i <= $li.length; i++){
                            if( $li.eq(i).data('date') == selectDate ){
                                $li.eq(i).addClass(opts.highColor);
                                break;
                            }
                        }
                        $('#date').val( $(this).data('date') );
                    }else if( $(this).hasClass('next') ){
                        if( opts.m >= 12 ){
                            opts.m = 0;
                            opts.y = +opts.y + 1;
                        }
                        opts.m = +opts.m + 1;   // + 字符串转数字
                        document.querySelector('.year-title').innerText = opts.y;
                        document.querySelector('.month-title').innerText = opts.m;
                        cale.init();

                        //选择日期高亮
                        var selectDate  = $(this).data('date'),
                            $li         = $('.cale-day li');

                        for(var i = 0; i <= $li.length; i++){
                            if( $li.eq(i).data('date') == selectDate ){
                                $li.eq(i).addClass(opts.highColor);
                                break;
                            }
                        }
                        $('#date').val( $(this).data('date') );
                    }

                    console.log( $('.cale-day li').not('.cur-date').hasClass('active') );
                    if( $('.cale-day li').not('.cur-date').hasClass('active') ){
                        $('.cale-day li[data-date='+ opts.y + '-' + cale.toDouble(opts.m) + '-' + cale.toDouble(opts.d) + ']').removeClass('active');
                        console.log( opts.y, cale.toDouble(opts.m), cale.toDouble(opts.d) );
                    }else{
                        $('.cale-day li[data-date='+ opts.y + '-' + cale.toDouble(opts.m+1) + '-' + cale.toDouble(opts.d) + ']').addClass('cur-date');    
                    }
                });
            },
            //补零
            toDouble: function (n){
                return n < 10 ? '0' + n : '' + n;
            }
        };

        cale.init();
        cale.onChange();
        cale.onSelect();
    }
})(jQuery);